import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import Students from '../views/Students.vue'
import StudentDetail from '../views/StudentDetail.vue'
import Classes from '../views/Classes.vue'
import Courses from '../views/Courses.vue'
import Grades from '../views/Grades.vue'
import Statistics from '../views/Statistics.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { title: '仪表盘', requiresAuth: true }
  },
  {
    path: '/students',
    name: 'Students',
    component: Students,
    meta: { title: '学生管理', requiresAuth: true }
  },
  {
    path: '/students/:id',
    name: 'StudentDetail',
    component: StudentDetail,
    meta: { title: '学生详情', requiresAuth: true },
    props: true
  },
  {
    path: '/classes',
    name: 'Classes',
    component: Classes,
    meta: { title: '班级管理', requiresAuth: true }
  },
  {
    path: '/courses',
    name: 'Courses',
    component: Courses,
    meta: { title: '课程管理', requiresAuth: true }
  },
  {
    path: '/grades',
    name: 'Grades',
    component: Grades,
    meta: { title: '成绩管理', requiresAuth: true }
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: Statistics,
    meta: { title: '统计分析', requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫，设置页面标题和权限检查
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态
  authStore.initAuth()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 学生管理系统`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    // 已登录用户访问登录页，跳转到仪表盘
    next('/dashboard')
  } else {
    next()
  }
})

export default router 